﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.AnalysisTools;

namespace ISchool
{
    class IBuffer
    {
        //作者：宋翔
        //执行图层的缓冲区效果
        [DllImport("user32.dll")]
        private static extern int PostMessage(IntPtr wnd,
                                              uint Msg,
                                              IntPtr wParam,
                                              IntPtr lParam);


        public IHookHelper mHookHelper = new HookHelperClass();
        //输入路径
        public string strInputLayerPath { get; set; }
        //输出路径
        public string strOutputPath { get; set; }
        //缓冲区的半径
        public double mBufferDistance;
        // 用于显示可用图层并加载到ComboBox中
        public ComboBox mComboBox;
        public string mDisUnits;
        //初始化
        public IBuffer(object hook)
        {
            this.mHookHelper.Hook = hook;
        }
        //设置显示图层容器
        public void setComboBoxLabel(ComboBox test)
        {
            this.mComboBox = test;
        }
        //设置缓冲距离
        public void setDistance(double x, string y)
        {
            mBufferDistance = x;
            mDisUnits = y;
        }

        //根据LayerName获取图层对象
        private IFeatureLayer getFeatureLayer(string LayerName)
        {
            IFeatureLayer pFeatureLayer = null;
            //遍历获取空间中地图Layer
            for (int i = 0; i < this.mHookHelper.FocusMap.LayerCount; i++)
            {
                ILayer mLayer = this.mHookHelper.FocusMap.get_Layer(i);
                if (mLayer.Name == LayerName)
                {
                    pFeatureLayer = mLayer as IFeatureLayer;
                }
            }
            //获取的图层不为空则图层返回值
            if (pFeatureLayer != null)
                return pFeatureLayer;
            else return null;
        }
        /// <summary>
        /// 加载图层名字到Combox并生成默认保存名
        /// </summary>
        public void FeatureLayerLoad()
        {
            //判断控件对象是否为空
            if (mHookHelper == null || mHookHelper.Hook == null || mHookHelper.FocusMap.LayerCount == 0)
            {
                return;
            }
            //获取矢量图层存入万能数据表中
            IEnumLayer layers = GetLayers();
            //指正指零
            layers.Reset();
            ILayer layer = null;
            //遍历并填入mComboBox中
            while ((layer = layers.Next()) != null)
            {
                mComboBox.Items.Add(layer.Name);
            }
            //填入控件
            if (mComboBox.Items.Count > 0)
            {
                mComboBox.SelectedIndex = 0;
            }
            strInputLayerPath = (string)mComboBox.SelectedItem;
            //生成默认路径
            string tempDir = System.IO.Path.GetTempPath();
            strOutputPath = System.IO.Path.Combine(tempDir, ((string)mComboBox.SelectedItem + "_buffer.shp"));
        }
        /// <summary>
        /// 另存为其他命名
        /// </summary>
        public void otherFeaturePath()
        {
            //文件名选择对话框
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.CheckPathExists = true;
            saveDlg.Filter = "Shapefile (*.shp)|*.shp";
            saveDlg.OverwritePrompt = true;
            saveDlg.Title = "Output Layer";
            saveDlg.RestoreDirectory = true;
            saveDlg.FileName = (string)strInputLayerPath + "_buffer.shp";
            DialogResult dt = saveDlg.ShowDialog();
            if (dt == DialogResult.OK)
            {
                strOutputPath = saveDlg.FileName;
            }
        }
        /// <summary>
        /// 执行缓冲区分析
        /// </summary>
        public void mBufferDo()
        {
            if (mBufferDistance == 0.0)
            {
                MessageBox.Show("参数错误");
                return;
            }
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(strOutputPath)) || (System.IO.Path.GetExtension(strOutputPath) != ".shp"))
            {
                MessageBox.Show("输出名错误或文件已存在");
                return;
            }
            if (mHookHelper.FocusMap.LayerCount == 0)
                return;
            //根据图层名获取图层
            IFeatureLayer layer = getFeatureLayer((string)mComboBox.SelectedItem);
            if (layer == null)
            {
                return;
            }
            //地理工具操作方法GP
                Geoprocessor gp = new Geoprocessor();
                gp.OverwriteOutput = true;
                ESRI.ArcGIS.AnalysisTools.Buffer buffer=null;
                try
                {
                    //缓冲区执行方法Buffer
                    buffer = new ESRI.ArcGIS.AnalysisTools.Buffer((object)layer, (object)strOutputPath, (object)(mBufferDistance.ToString() + " " + mDisUnits));
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            //执行缓冲区分析
                IGeoProcessorResult results = gp.Execute(buffer, null) as IGeoProcessorResult;
                if (results.Status != esriJobStatus.esriJobSucceeded)
                {
                    MessageBox.Show("Sory,I'm Failed");
                }
                else
                {

                }

        }
        private IEnumLayer GetLayers()
        {
            UID uid = new UIDClass();
            //根据图层ID特性获取矢量图层,40A9E885-5533-11d0-98BE-00805F7CED21为矢量shp文件id
            //详见IOveryLay
            uid.Value = "{40A9E885-5533-11d0-98BE-00805F7CED21}";
            //数据图层存入表中
            IEnumLayer layers = mHookHelper.FocusMap.get_Layers(uid, true);
            return layers;
        }
    }
}
